<template>
  <div>
    <div v-show="!baseOptions.read_model" class="markdown" id="markdown"></div>
    <!--    <div style="height: 100vh"   id="read_modeview">-->
    <!--    </div>-->
    <div v-show="baseOptions.read_model" class="preview-vditor">
      <div class="vditor-preview" id="read_modeview">
      </div>
    </div>

    <div @click="rightDrawer = true" class="more">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" data-v-3ce77d8f="">
        <path fill="currentColor"
              d="M160 448a32 32 0 0 1-32-32V160.064a32 32 0 0 1 32-32h256a32 32 0 0 1 32 32V416a32 32 0 0 1-32 32H160zm448 0a32 32 0 0 1-32-32V160.064a32 32 0 0 1 32-32h255.936a32 32 0 0 1 32 32V416a32 32 0 0 1-32 32H608zM160 896a32 32 0 0 1-32-32V608a32 32 0 0 1 32-32h256a32 32 0 0 1 32 32v256a32 32 0 0 1-32 32H160zm448 0a32 32 0 0 1-32-32V608a32 32 0 0 1 32-32h255.936a32 32 0 0 1 32 32v256a32 32 0 0 1-32 32H608z"></path>
      </svg>
    </div>

    <!--    <img  src="@assets/svg/more.svg" @click="rightDrawer = true"/>-->
  </div>


  <el-drawer
      title="更多设置"
      v-model="rightDrawer"
      size="30%"
      close-on-click-modal
      close-on-press-escape
      :with-header="false"
  >
    <div class="rightDrawerContent">

      <div class="card">
        <h1>导出</h1>

        <div class="right_menu_btn">
          <el-button style="color: #1d2125" type="text" @click="exportPDF">导出PDF</el-button>
        </div>

        <div class="right_menu_btn">
          <el-button style="color: #1d2125" type="text" @click="exportMarkDown">导出MarkDown</el-button>
        </div>

        <!--        <el-divider></el-divider>-->

        <!--        <div class="right-item">-->
        <!--          <span>启动时加载帮助文档</span>-->
        <!--          <el-switch v-model="options.load_help_onboot" class="drawer-btn" />-->
        <!--        </div>-->

      </div>

      <div class="card">
        <h1>页面</h1>
        <div class="right-item">
          <span>阅读模式</span>
          <el-switch v-model="baseOptions.read_model" class="drawer-btn" @click="switchReadModel"/>
        </div>

        <el-divider></el-divider>

        <h1>编辑模式</h1>
        <el-radio-group v-model="editMode" size="mini" :change="setEditMode(editMode)"
                        :disabled="baseOptions.read_model">
          <el-radio label="ir">即时渲染</el-radio>
          <el-radio label="sv">分屏预览(源码模式)</el-radio>
          <el-radio label="wysiwyg">所见即所得</el-radio>
        </el-radio-group>

        <el-divider></el-divider>

        <h1>主题设置</h1>
        <!--      <div class="right-item">-->
        <!--        <span>夜间模式</span>-->
        <!--        <el-switch v-model="nightMode" class="drawer-btn" :change="switchDarkModel(nightMode)"/>-->
        <!--      </div>-->

        <div class="right-item">
          <span>代码主题</span>
          <el-dropdown trigger="click" @command="switchTheme2" class="drawer-btn">
              <span class="el-dropdown-link">
                {{ options.preview.hljs.style }}<el-icon size="14"><arrow-down/></el-icon>
              </span>
            <template #dropdown>
              <el-dropdown-menu style="overflow-y: scroll;height: 420px">
                <el-dropdown-item
                    v-for="i in codeThemes"
                    :key="i"
                    :command="{codeTheme:i}"
                >
                  {{ i }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="right-item">
          <span>内容主题</span>
          <el-dropdown trigger="click" @command="switchTheme2" class="drawer-btn"
                       placement="top-start"
          >
                <span class="el-dropdown-link">
                 {{ options.preview.theme.current }}<el-icon size="14"><arrow-down/></el-icon>
                </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                    v-for="it in contentThemes"
                    :key="it"
                    :command="{contentTheme:it}"
                >
                  {{ it }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

      </div>

      <div class="card">
        <h1>其他设置</h1>

        <div class="right-item">
          <span>代码块开启行号</span>
          <el-switch v-model="options.preview.hljs.lineNumber" class="drawer-btn" :disabled="baseOptions.read_model"/>
        </div>
        <div class="right-item">
          <span>开启计数器</span>
          <el-switch v-model="options.counter.enable" class="drawer-btn" :disabled="baseOptions.read_model"/>
        </div>

        <el-divider></el-divider>

        <div class="right-item">
          <span>文档目录</span>
          <el-input
              size="mini"
              v-model="baseOptions.doc_root_path"
              placeholder="请设置一个路径"
              @input="docPathChange=true"

          >
          </el-input>
          <el-button size="mini"
                     type="primary"
                     :disabled="!docPathChange"
                     class="drawer-btn"
                     @click="updataDocPathOptions"
          >
            修改
          </el-button>
          <!--            <el-switch v-model="count" class="drawer-btn" :change="switchCount(count)"/>-->
        </div>

      </div>

    </div>

  </el-drawer>

</template>

<script>

import "vditor/src/assets/scss/index.scss";
import emitter from "@/common/util/mitt.js";
import {initMarkDown, updataDoc, saveDoc, renderOutline} from "@/common/markdown";
import {
  markDownOptions, upDataEditMode,
  upDataThemes, updataOptions, getBaseOptions
} from "@/common/settings";
import {onMounted, onUnmounted} from "vue";
import {ElNotification} from 'element-plus'
import router from '../router'
import {ref, toRaw, watch, reactive} from "vue";
import {ArrowDown, Menu, Grid} from '@element-plus/icons'
import {exportAndDownloadPdf, exportMarkdown} from "@/common/util/export";

export default {

  name: 'EditContent',
  components: {
    ArrowDown
  },
  setup() {
    const rightDrawer = ref(false);
    let editContent = null;
    let editMode = ref("ir");
    let docPathChange = ref(false);
    let timer = null;
    let lockFile = false;
    //当前节点文件信息
    var currentNode = null;
    var baseOptions = reactive(getBaseOptions());
    var options = ref(markDownOptions());

    var docQueue = {}

    const contentThemes = ref(["ant-design", "light", "wechat"]);
    const codeThemes = ref(["algol", "arduino", "colorful", "emacs", "fruity", "github", "igor", "lovelace", "manni",
      "monokai", "monokailight", "native", "rainbow_dash", "rrt", "swapoff", "trac", "vs", "ant-design"]);


    let init = () => {
      editMode.value = options.value.mode
      editContent = initMarkDown(options.value, "markdown", onMarkDownChange)


      // 监听事件，更新数据
      emitter.on('update-markdown', (node) => {
        currentNode = node;
        updata(currentNode)
      })


      timer = setInterval(() => {
        if (!lockFile && !baseOptions.read_model) {
          renderOutline(editContent, "markdown-outline")
          reWrite()
        }
      }, 2000)

      watch(() => [options.value.counter, options.value.preview.hljs.lineNumber], (newValue, oldValue) => {
            options.value = updataOptions(toRaw(options.value))
            reloadMarkDown()
          },
          //深度监听
          {deep: true}
      );
    }

    let switchReadModel = () =>{
      updataBaseOptions()
      reloadMarkDown()
    }



    let onMarkDownChange = (str) => {
      let queue = {content: str, path: currentNode.path, isWrite: false}
      let queName = queue.path
      docQueue[queName] = queue
    }

    let reWrite = () => {
      for (let key in docQueue) {
        let value = docQueue[key]
        if (!value.isWrite) {
          saveDoc(value)
        }
      }
    }


    let updata = (node) => {

      updataDoc(node, "#markdown", editContent,
          {
            enable: baseOptions.read_model, element: document.getElementById("read_modeview"),
            options: toRaw(options.value), outline: document.getElementById("markdown-outline")
          })
    }

    let reloadMarkDown = () => {
      if (baseOptions.read_model) {
        updata(currentNode)
      } else {
        // let text = editContent.getValue()
        editContent.destroy()
        editContent = initMarkDown(options.value, "markdown", onMarkDownChange, currentNode)
      }

    }


    let switchTheme2 = (themes) => options.value = upDataThemes(themes, toRaw(options.value), editContent)
    let setEditMode = (mode) => options.value = upDataEditMode(mode, toRaw(options.value), editContent)

    let updataBaseOptions = () => {
      baseOptions = updataOptions(toRaw(baseOptions))
    }

    let updataDocPathOptions = () => {
      window.newDir(toRaw(baseOptions.doc_root_path), (err) => {
        if (err) {
          ElNotification({title: '错误', message: err, type: 'error',})
        } else {
          ElNotification({title: '成功', message: "修改成功", type: 'success',})
          updataBaseOptions()
          window.setDocHomeDir(baseOptions.doc_root_path)
          router.push({
            name: 'Splash',
            params: {reload: true}
          })
        }
      })
    }

    let exportPDF = () => {

      rightDrawer.value = false
      let filename = currentNode.name + ".pdf";
      let element = document.getElementById('read_modeview')

      if (!baseOptions.read_model) {
        baseOptions.read_model = true
        reloadMarkDown()

        setTimeout(function () {
          exportAndDownloadPdf(filename, element,()=>{baseOptions.read_model = false; reloadMarkDown()})
        },1000)
      }else {
        exportAndDownloadPdf(filename, element)
      }



    }

    let exportMarkDown = () => {
      window.readFile(currentNode.path, (err, data) => {
        if (err) {
          ElNotification({title: '错误', message: '文件读取失败！\n' + err, type: 'error',})
        } else {
          exportMarkdown(data, currentNode.name + ".md")
        }
      });
    }


    onMounted(() => {
      init()
    })

    // 卸载
    onUnmounted(() => {
      emitter.off('update-markdown', () => {
        clearInterval(timer)
        editContent.destroy()
      })
    })

    return {
      options,
      editContent, exportPDF, exportMarkDown, contentThemes, codeThemes, docPathChange,
      rightDrawer, setEditMode, editMode, baseOptions, updataDocPathOptions,switchReadModel,
      switchTheme2
    }
  }

}
</script>

<style scoped>
.markdown {
  border: unset
}

.more {
  width: 30px;
  height: 30px;
  position: absolute;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  /*color: #e9ecef;*/
  transition: all .5s;
}

.more:hover {
  transform: rotate(225deg);
}

.card {
  margin-bottom: 10px;
  overflow: scroll;
  padding: 10px;
  background: #ffffff;
  box-shadow: 0px 0px 15px #f0f0f0;
}

.drawer-btn {
  position: relative;
  float: right;
}

.right-item {
  margin-bottom: 15px;
}

.rightDrawerContent {
  overflow: scroll;
  height: 100vh;
}

.rightDrawerContent::-webkit-scrollbar {
  display: none
}

.el-dropdown-link {
  color: #4ca0fb;
  child-align: bottom;
}

.preview-vditor {
  height: 100vh;
  background: #fafbfc;
  padding: 20px;
  overflow-y: auto;
}

.vditor-preview {
  /*overflow: scroll;*/
  padding: 15px;
  background: #ffffff;
  box-shadow: 0px 0px 15px #f0f0f0;
}

.right_menu_btn {
  width: 100%;
}

.right_menu_btn:hover {
  background: #e9ecef;
}

</style>

<style>
.el-drawer__body {
  padding: 13px !important;
  background: #f9fafb;

}

.el-input__inner {
  border-radius: 0px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: unset;
  margin-right: unset;
  border-bottom: 1px solid #dbdbdb;
  border-top: 0px;
  border-left: 0px;
  border-right: 0px;
  padding-left: unset;
  padding-right: unset;

}


</style>
